package com.genersoft.iot.vmp.gb28181.third.event;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.genersoft.iot.vmp.common.VideoManagerConstants;
import com.genersoft.iot.vmp.gb28181.bean.Device;
import com.genersoft.iot.vmp.gb28181.third.callback.CallBackService;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @author XJW
 */
@Component
public class CallBackEventListener implements ApplicationListener<CallBackEvent> {

    private static final Logger logger = LoggerFactory.getLogger(CallBackEventListener.class);

    private static final Cache<String, LocalDateTime> CACHE = CacheUtil.newLFUCache(1000, Duration.ofMinutes(10).getSeconds() * 1000);

    @Autowired
    SIPCommander sipCommander;
    @Autowired
    private CallBackService callBackService;

    @Override
    public void onApplicationEvent(CallBackEvent event) {
        Device device = event.getDevice();

        switch (event.getFrom()) {
            case VideoManagerConstants.EVENT_CALLBACK_KEEPALIVE:
                if (!CACHE.containsKey(device.getDeviceId())) {
                    sipCommander.catalogQuery(device, null);
                } else {
                    LocalDateTime lastTime = CACHE.get(device.getDeviceId());
                    LocalDateTime plusMinutes = LocalDateTime.now().plusMinutes(-5);
                    boolean status = plusMinutes.isAfter(lastTime);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Check time [{}] plusMinutes:{} lastTime {} status {}", device.getDeviceId(), plusMinutes, lastTime, status);
                    }
                    if (status) {
                        sipCommander.catalogQuery(device, null);
                    }
                }
                break;
            case VideoManagerConstants.EVENT_CALLBACK_CATALOG:
                CACHE.put(device.getDeviceId(), LocalDateTime.now());
                callBackService.channelUpate(event.getDeviceChannels());
                break;
            default:
                logger.error("Callback from error [{}]", event.getFrom());
        }
    }
}
